package com.fbinggun.fbinggunutil.plugin.nbt;

import de.tr7zw.nbtapi.NBT;
import de.tr7zw.nbtapi.NBTCompound;
import de.tr7zw.nbtapi.NBTItem;
import org.bukkit.inventory.ItemStack;

import java.util.HashMap;
import java.util.Map;
/**
 * NBTAPI 插件ItemNBT API
 */
public class ItemNBT {

    public static ItemStack setInt(ItemStack itemStack,String key,Integer o){
        NBTItem nbtItem = new NBTItem(itemStack);
        if(key.contains("_")){
            String[] args =key.split("_");
            NBTCompound compound = null;
            Map<Integer,NBTCompound> map = new HashMap<>();
            for(int x=0;x<args.length;x++){
                if(x== args.length-1){
                    break;
                }
                if(compound==null){
                    compound= nbtItem.addCompound(args[x]);
                }else {
                    compound=compound.addCompound(args[x]);
                }
                map.put(args.length-x-1, compound);
            }
            if(map.size()==0){
                nbtItem.setInteger(key,o);
            }else {
                NBTCompound compound2 = null;
                for(int x=0;x<map.size();x++){
                    if(compound2==null){
                        compound2 =map.get(x);
                        compound2.setInteger(args[args.length-1],o);
                    }else {
                        NBTCompound n = map.get(x);
                        n.mergeCompound(compound2);
                        compound2=n;
                    }
                }
                nbtItem.mergeCompound(compound2);
            }
            return nbtItem.getItem();

        }else {
            nbtItem.setInteger(key,o);
            return nbtItem.getItem();
        }
    }
}
